package com.lwz.startdemo

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.concurrent.thread

/**
 * @Description: 类作用描述
 * @Author: chad
 * @CreateDate: 2025/5/15 12:54
 * @Version: 1.0
 */
class MainViewModel(initValue:Int) :ViewModel(){
    val counter :LiveData<Int>
        get() = _counter

    private val _counter = MutableLiveData<Int>()

    init {
        _counter.value = initValue
    }

    fun plusOne(){
       val count = counter.value ?: 0
        _counter.value = count.plus(1)
    }

    /**
     * 子线程用 postValue
     */
    fun plusOneThread(){
        thread {
            GlobalScope.launch {
                delay(3000)

                val count = _counter.value ?: 0
                _counter.postValue(count.plus(1))
            }
        }

    }


    fun clear(){
        _counter.value = 0
    }

}